package com.lx.boot.web.convert.serializer;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.lx.annotation.Note;
import com.lx.boot.web.convert.DFunction;
import com.lx.util.secure.algorithm.coder.CoderType;

import java.lang.annotation.*;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.TYPE,ElementType.PARAMETER})
@Documented
@JacksonAnnotationsInside
@Serializer(value = EecoderSerializer.class,function = EecoderSerializer.EecoderDFunction.class)
public @interface EecoderSerializer {

    @Note("指定解码类型")
    CoderType value();

    @Note("指定其他字段进行解码")
    String mapper() default "";

    public static class EecoderDFunction implements DFunction<SerializerPara, EecoderSerializer, Object> {
        @Override
        public Object apply(SerializerPara para, EecoderSerializer convert) {
            Object value = para.getValue(convert.mapper());
            Class filedType = para.getFiledType(convert.mapper());
            if (String.class.isAssignableFrom(filedType)){
                if (value instanceof byte[] bytes){
                    return convert.value().encodeToString(bytes);
                }
                if (value instanceof String data){
                    return convert.value().encodeToString(data);
                }
            }else if (byte[].class.isAssignableFrom(filedType)){
                if (value instanceof byte[] bytes){
                    return convert.value().encode(bytes);
                }
                if (value instanceof String data){
                    return convert.value().encode(data);
                }
            }
            throw new RuntimeException("请检查待解码/解密的参数类型是否为String 或 byte[]");
        }
    }

}
